package com.pc.tas.util;

import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SearchEngineUtils {
	private static Logger log = Logger.getLogger(SearchEngineUtils.class);
	private static SearchEngineUtils instance;
	Pattern p = Pattern.compile("http:\\/\\/.*\\.(google\\.com(:\\d{1,}){0,1}\\/|" +
	        "google\\.cn(:\\d{1,}){0,1}\\/|google\\.com.hk(:\\d{1,}){0,1}\\/|baidu\\.com(:\\d{1,}){0,1}\\/|" + 
	        "yahoo\\.com(:\\d{1,}){0,1}\\/|iask\\.com(:\\d{1,}){0,1}\\/|" +
	        "sogou\\.com(:\\d{1,}){0,1}\\/|163\\.com(:\\d{1,}){0,1}\\/|" +
	        "lycos\\.com(:\\d{1,}){0,1}\\/|aol\\.com(:\\d{1,}){0,1}\\/|" +
	        "3721\\.com(:\\d{1,}){0,1}\\/|search\\.com(:\\d{1,}){0,1}\\/|" +
	        "soso.com(:\\d{1,}){0,1}\\/|zhongsou\\.com(:\\d{1,}){0,1}\\/|" +
	        "alexa\\.com(:\\d{1,}){0,1}\\/)");
	
	Pattern senamep =  Pattern.compile("(\\.com(:\\d{1,}){0,1}\\/|\\.cn(:\\d{1,}){0,1}\\/|\\.org(:\\d{1,}){0,1}\\/|\\.com.hk(:\\d{1,}){0,1}\\/)");
	Pattern keywordp;
	
	private SearchEngineUtils() {
		StringBuffer sb=new StringBuffer();
		sb.append("(google\\.[a-zA-Z\\.]+/.+[\\&|\\?]q=([^\\&]*)")
        .append("|iask\\.[a-zA-Z]+/.+[\\&|\\?]k=([^\\&]*)")
        .append("|iask\\.[a-zA-Z]+/.+[\\&|\\?]_searchkey=([^\\&]*)")
        .append("|sogou\\.[a-zA-Z]+/.+[\\&|\\?]query=([^\\&]*)")
        .append("|163\\.[a-zA-Z]+/.+[\\&|\\?]q=([^\\&]*)")
        .append("|yahoo\\.[a-zA-Z]+/.+[\\&|\\?]p=([^\\&]*)")
        .append("|baidu\\.[a-zA-Z]+/.+[\\&|\\?]wd=([^\\&]*)")
        .append("|baidu\\.[a-zA-Z]+/.+[\\&|\\?]word=([^\\&]*)")
        .append("|lycos\\.[a-zA-Z]+/.*[\\&|\\?]query=([^\\&]*)")
        .append("|aol\\.[a-zA-Z]+/.+[\\&|\\?]encquery=([^\\&]*)")
        .append("|3721\\.[a-zA-Z]+/.+[\\&|\\?]p=([^\\&]*)")
        .append("|3721\\.[a-zA-Z]+/.+[\\&|\\?]name=([^\\&]*)")
        .append("|search\\.[a-zA-Z]+/.+[\\&|\\?]q=([^\\&]*)")
        .append("|soso\\.[a-zA-Z]+/.+[\\&|\\?]w=([^\\&]*)")
        .append("|zhongsou\\.[a-zA-Z]+/.+[\\&|\\?]w=([^\\&]*)")
        .append("|alexa\\.[a-zA-Z]+/.+[\\&|\\?]q=([^\\&]*)")
        .append(")");
		
		keywordp = Pattern.compile(sb.toString());
	}
	
	public synchronized static SearchEngineUtils getInstance() {
		if(instance == null) {
			instance = new SearchEngineUtils();
		}
		return instance;
	}
	
	
	private String insteadCode(String str,String code){	    
	    Matcher m=senamep.matcher(str);
	    String s=m.replaceAll(code);
	    return s;
	}
	
	//获取搜索引擎的名称
	public String getSearchEngine(String refUrl) {
	    if(refUrl.length()>11) {	      
	      Matcher m = p.matcher(refUrl);
	      //如果来源地址可以匹配以上的pattern
	      if (m.find()) {
	    	  //因为m.group(0)是域名，m.group(1)才是我们最合适我们所要的
	        return insteadCode(m.group(1),"");//把.com,.cn,.org替换为""
	      }
	    }	    
	    return null;
	}	
	
	//获取搜索关键字
	public String getKeyword(String refererUrl) {	     
	     if(refererUrl!=null) {	       
	       Matcher m = keywordp.matcher(refererUrl);
	       return decoderKeyword(m,refererUrl);
	     }
	     return null;
	}
	
	private String decoderKeyword(Matcher m,String refererUrl) {
	   String keyword=null;
	   String encode="UTF-8";
	   String searchEngine=getSearchEngine(refererUrl);
	   if(searchEngine!=null) {
	     if ((checkCode("3721|iask|sogou|163|baidu|soso|zhongsou",searchEngine)
		 ||(checkCode("yahoo",searchEngine)&&!checkCode("ei=utf-8",refererUrl.toLowerCase()))))
	     {
	       encode = "GBK";
	     }
	     
	     if (m.find()) {
	       for (int i = 2; i <= m.groupCount(); i++) {
	         if (m.group(i) != null) {
	           try {
	             keyword = URLDecoder.decode(m.group(i), encode);
	           }
	           catch(UnsupportedEncodingException e) {
	             log.error(e);
	           }
	           break;
	         }
	       }
	     }
	   }
	   return keyword;
	}
	
	private boolean checkCode(String regEx,String str){
	    Pattern p=Pattern.compile(regEx);
	    Matcher m=p.matcher(str);
	    return m.find();
	}

}
